﻿#include <QUrl>
#include "TcpModbusServer.h"

TcpModbusServer::TcpModbusServer(QObject *parent) : BaseCommunication(parent)
{
    _modbusServer=new QModbusTcpServer(this);
    connect(_modbusServer, &QModbusTcpServer::stateChanged, this, &TcpModbusServer::onStateChanged);
    connect(_modbusServer, &QModbusTcpServer::dataWritten, this, &TcpModbusServer::onDataWritten);
}

bool TcpModbusServer::Connect()
{
    const QUrl url = QUrl::fromUserInput(_communicationParam);
    _modbusServer->setConnectionParameter(QModbusDevice::NetworkPortParameter, url.port());
    _modbusServer->setConnectionParameter(QModbusDevice::NetworkAddressParameter, url.host());

    // 设置Modbus数据单元，类型为保持寄存器
    QModbusDataUnitMap reg;
    reg.insert(QModbusDataUnit::HoldingRegisters, {QModbusDataUnit::HoldingRegisters, 0, 10});
    _modbusServer->setMap(reg);
    _modbusServer->setServerAddress(1);

    // 初始化保持寄存器的值
    for (int i = 0; i < 10; ++i) {
        _modbusServer->setData(QModbusDataUnit::HoldingRegisters, i, 0);
    }

    return _modbusServer->connectDevice();
}

bool TcpModbusServer::IsConnected()
{
    return true;
}

void TcpModbusServer::Dispose()
{
    _modbusServer->disconnectDevice();
}

void TcpModbusServer::WriteRegister(QModbusDataUnit::RegisterType registerType, int address, int val)
{
    _modbusServer->setData(QModbusDataUnit::HoldingRegisters,address,val);
}

void TcpModbusServer::onStateChanged(QModbusDevice::State state)
{
    qDebug() << "Modbus server state changed:" << state;
}

void TcpModbusServer::onDataWritten(QModbusDataUnit::RegisterType table, int address, int size)
{
    quint16 value;
    _modbusServer->data(table, address, &value);
    emit DataWritten(table,address,value);
}

void TcpModbusServer::SetOtherConfig(QJsonObject other)
{
    BaseCommunication::SetOtherConfig(other);
}
